// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	async userlistAction(){
		//取出当前店的员工

		let page = JSON.parse(this.post('page'));
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.shop_userinfo.departmentid;

		let where = {
			'u.shopid':shopid,
			'u.isdisable':page.zt,
			'u.isdelete': 0,
			'u.username|u.name|u.worknum':['like','%'+search+'%']
		}

		let data = await this.model('or_app_user')
							.alias('u')
							.field('u.id,u.username,u.name,u.ismanage,u.sex,u.isdisable, u.remarks,d.name as departmentname,d.id as departmentid,p.name as positionname, p.id as pid,s.name as zhichengname, s.id as sid,u.addtime,u.xiaozuid,u.bumenid,u.departmentid,u.worknum')
							.join("think_or_department d ON u.departmentid = d.id")
							.join("think_or_position p ON u.positionid = p.id")
							.join("think_or_position s ON u.zhichengid = s.id")
							.where(where)
							.page(pages, limits)
							.order("u.id DESC")
							.countSelect();

		return this.json(data);
	}

	async adduserAction(){
		let data = this.post();
		let addtime = Math.round(new Date().valueOf()/1000);
		let shopid = this.shop_userinfo.departmentid;
		// 判断当前分店员工工号是否重复
		let repeatWorknum = await this.model('or_app_user').where({isdelete: 0, shopid: shopid, worknum: data.worknum}).find();
		if (!think.isEmpty(repeatWorknum)) {
			return this.fail('工号重复');
		}
		// 取机构id（机构唯一）标准#010
		let orcode = await this.model('or_department').where({id: shopid}).getField('orcode', true)
		let is_exist = await this.model('or_app_user')
				.alias('u')
				.join('`think_or_department` d on u.departmentid = d.id')
				.where({isdelete: 0, username:data.username, orcode: orcode})
				.find();

		if(!think.isEmpty(is_exist)){
			return this.fail('该登陆账号已经存在！');
		}

		let bumenInfo = await this.model('or_department').where({id: data.departmentid}).find()

		switch(bumenInfo.floor){
			case 1:
				data.bumenid = 0
				data.xiaozuid = 0
				break
			case 2:
				data.bumenid = bumenInfo.id
				data.xiaozuid = 0
				break
			case 3:
				data.bumenid = bumenInfo.pid
				data.xiaozuid = bumenInfo.id
				break 
		}
	
		data.password = think.md5(data.username);
		data.addtime = addtime;
		data.shopid = this.shop_userinfo.departmentid;

		let res = await this.model('or_app_user').add(data);
		return res?this.success("添加成功！"):this.fail('添加失败！');
	}
	
	// 编辑当前用户
	async edituserAction(){
		let data = this.post(); 
		// 取机构id（机构唯一）标准#010
		let repeatWorknum = await this.model('or_app_user')
				.alias('ap')
				.join('`think_or_app_user` au on au.id = ap.id')
				.where({'ap.isdelete': 0, 'ap.departmentid':data.departmentid,'au.worknum':data.worknum,'ap.id':['!=', data.id]})
				.find()
		if (!think.isEmpty(repeatWorknum)) {
			return this.fail('工号重复');
		}
		let orcode = await this.model('or_app_user')
				.alias('u')
				.join('`think_or_department` d on u.departmentid = d.id')
				.where({'u.id': data.id})
				.getField('d.orcode', true)
		let is_exist = await this.model('or_app_user')
				.alias('u')
				.join('`think_or_department` d on u.departmentid = d.id')
				.where({'u.isdelete': 0, username:data.username, orcode: orcode, 'u.id':["!=",data.id]})
				.find();
		if(!think.isEmpty(is_exist)){
			return this.fail('该登陆账号已经存在！');
		}

		let bumenInfo = await this.model('or_department').where({id: data.departmentid,isdisable:0}).find()
		
		if(!bumenInfo.id){ 
			return this.fail('该部门已关闭，请重新选择部门！');
		}
		switch(bumenInfo.floor){
			case 1:
				data.bumenid = 0;
				data.xiaozuid = 0;
				break
			case 2:
				data.bumenid = bumenInfo.id;
				data.xiaozuid = 0;
				break
			case 3:
				data.bumenid = bumenInfo.pid;
				data.xiaozuid = bumenInfo.id;
				break 
		}

		data.password = think.md5(data.username);
		data.remarks =  data.remarks?data.remarks:(data.remarks = '无');
		data.isdisable = 0;
		let res = await this.model('or_app_user').update(data);
		return res?this.success("编辑成功！"):this.fail('编辑失败！');
	}
	
	// 停用、启用当前用户
	// 一旦弃用将不再显示
	async unstopAction(){
		let id = this.post('id');
		let model = this.model('or_app_user');
		await model.transaction(async ()=>{
			try {

				let you = await this.model('or_allotuser').db(model.db()).where({uid: id}).select();
				if (!think.isEmpty(you)) {
					let shanchu = await this.model('or_allotuser').db(model.db()).where({uid: id}).delete();
					if (!shanchu) {
						await model.rollback();
						return this.fail('停职失败');
					}
				}

				let res = await model.where({id:id}).update({isdisable:1,ismanage:0, worknum: ''});
				if (!res) {
					await model.rollback();
					return this.fail('停职失败');
				}
				
				await model.commit();
				return this.success('停职成功');
			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('停职失败');
			}
		})
	}

	// 修改员工所在部门，如果当前员工为管理层，则取消其管理层权限，（ismanage : 0）
	async edituserdepartmentAction(){
		if (this.isPost) {
			let editData = this.post();
			console.log(editData);
			editData.ismanage = 0;
			editData.departmentid = editData.depid
			let bumenInfo = await this.model('or_department').where({id: editData.depid}).find()
			switch(bumenInfo.floor){
				case 1:
					editData.bumenid = 0
					editData.xiaozuid = 0
					break
				case 2:
					editData.bumenid = bumenInfo.id
					editData.xiaozuid = 0
					break
				case 3:
					editData.bumenid = bumenInfo.pid
					editData.xiaozuid = bumenInfo.id
					break 
			}
			let data = await this.model('or_app_user').where({id:editData.id}).update(editData);
			return data?this.success({info:'修改部门成功'}):this.fail('修改部门失败');
		}
		let curdepartmentid = this.shop_userinfo.departmentid;
		let departments = await this.model('or_department').where({pid:curdepartmentid,isdisable:0}).select();
		let did = await this.model('or_department').where({id:curdepartmentid}).find();
		let groups = [];
		if (departments.length) {
			for (var i = 0, depLen = departments.length; i < depLen; i++) {
				groups.push(await this.model('or_department').where({pid:departments[i].id,isdisable:0}).select());
			}
		}
		departments.push(did);
		let shops = {
			dep : departments,
			gro : groups,
		}
		return this.json(shops)
	}

	// 获取顾客分配人员信息列表
	async allotusersAction(){
		let guestid = this.post('guestid');
		let userlist = await this.model().query('select u.id,u.name,u.username,zw.name as zhiwei,zc.name as zhicheng,d.name as dname,d.id as did,u.bumenid,u.xiaozuid from `think_or_app_user` as u left join `think_or_allotuser` a on u.id=a.uid left join `think_or_position` zw on u.positionid=zw.id left join `think_or_position` zc on zc.id=u.zhichengid left join `think_or_department` d on d.id=u.departmentid where a.gid='+guestid);
		return this.json(userlist);
	}
	
	// 查看用户信息
	async userinfoAction () {
		let id = this.post('id')
		let info = await this.model('or_app_user').where({id: id}).find()
		return this.json(info)
	}

	/*async fuzhiAction () {
		let id = this.post('id')
		let res = await this.model('or_app_user').where({id: id}).update({isdisable:0})
		return res?this.success("操作成功！"):this.fail('操作失败！');
	}*/

	// 重置当前员工帐号和密码
	async resetpasswordAction(){
		let uid = this.get('id');

		let uinfo = await this.model('or_app_user').where({id: uid}).find();

		let password = think.md5(uinfo.username);

		let resetRes = await this.model('or_app_user').where({id: uid}).update({password: password});

		return resetRes?this.success('重置员工密码成功'):this.fail('重置员工密码失败');
	}

	// 获取当前分店所有有效部门和小组列表
	async getdepartmentlistAction(){
		let shopid = this.shop_userinfo.departmentid;

		let shop = await this.model('or_department').where({id: shopid}).find();

		let bumens = await this.model('or_department').where({pid: shopid, isdisable: 0}).select();

		let groups = await this.model('or_department')
				.alias('x')
				.field('x.*')
				.join('`think_or_department` b on b.id=x.pid')
				.where({'b.pid': shopid, 'x.isdisable': 0})
				.select();

		let data = {
			shop: shop,
			bumens: bumens,
			groups: groups
		}

		return this.json(data);
	}

}